package com.three.monitor;

import com.codahale.metrics.*;
import com.codahale.metrics.health.HealthCheckRegistry;
import com.codahale.metrics.health.jvm.ThreadDeadlockHealthCheck;
import com.codahale.metrics.jvm.*;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.lang.management.ManagementFactory;
import java.util.concurrent.TimeUnit;

/**
 * 指标记录</br>
 * 定时写到日志中</br>
 * 可以定义自己的日志记录，持久化，或者推送到监控系统</br>
 * Created by ziqingwang on 2016/11/25.</br>
 */
@Component
public class JvmMetricsConfig {
    private static MetricRegistry metricRegistry = new MetricRegistry();
    private static HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry();

    @PostConstruct
    public void initMetrics(){
//        metricRegistry.register("jvm.gc", new GarbageCollectorMetricSet());
//        metricRegistry.register("jvm.memory", new MemoryUsageGaugeSet());
//        metricRegistry.register("jvm.thread-states", new ThreadStatesGaugeSet());
//        metricRegistry.register("jvm.fd.usage", new FileDescriptorRatioGauge());
//        metricRegistry.register("jvm.buffers", new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer()));
//        healthCheckRegistry.register("deadlocks", new ThreadDeadlockHealthCheck());
//        //五分钟上报一次
//        Slf4jReporter reporter = Slf4jReporter.forRegistry(metricRegistry)
//                .outputTo(LoggerFactory.getLogger("logger-metrics")).withLoggingLevel(Slf4jReporter.LoggingLevel.WARN).build();
//        reporter.start(5, TimeUnit.MINUTES);
    }
    public static MetricRegistry getMetric() {
        return metricRegistry;
    }

    public static HealthCheckRegistry getHealthCheck() {
        return healthCheckRegistry;
    }

    public static Meter meter(Class<?> klass, String... names) {
        return metricRegistry.meter(MetricRegistry.name(klass, names));
    }

    public static Timer timer(Class<?> klass, String... names) {
        return metricRegistry.timer(MetricRegistry.name(klass, names));
    }
}
